package com.wunong.smart.commission.domain.state;

import com.wunong.smart.commission.client.enums.CommissionStatusEnum;
import com.wunong.smart.domain.component.register.BaseSingletonInitBean;
import com.wunong.smart.domain.platform.exception.IllegalOperateException;
import org.apache.commons.collections.MapUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author create by zealot.zt
 */
@Component(CommissionStateFactory.BEAN_NAME)
public class CommissionStateFactory extends BaseSingletonInitBean {

    public static final String BEAN_NAME = "com.wunong.smart.commission.domain.state.CommissionStateFactory";

    private static Map<CommissionStatusEnum, CommissionState> hashMap = new HashMap<>();

    @Override
    protected void onInit(ApplicationContext context) {
        Map<String, CommissionState> beans = applicationContext.getBeansOfType(CommissionState.class);
        if (MapUtils.isNotEmpty(beans)) {
            beans.forEach((k, v) -> {
                if (hashMap.containsKey(v.getStatusEnum())) {
                    throw new IllegalOperateException("亲，存在相同的状态机服务，状态:" + v.getStatusEnum());
                }
                hashMap.put(v.getStatusEnum(), v);
            });
        }
    }

    /**
     * 根据状态获取对应的状态机
     *
     * @param statusEnum
     * @return
     */
    public static CommissionState getState(CommissionStatusEnum statusEnum) {
        if (Objects.isNull(statusEnum)) {
            return hashMap.get(CommissionStatusEnum.PROCESSING);
        }

        return hashMap.get(statusEnum);
    }

}
